/**
 * 
 */
package com.pos.modules.storage;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pos.BaseActivity;
import com.pos.R;
import com.pos.modules.ScannerActivity;
import com.pos.net.base.Request.Method;
import com.pos.net.netparam.NetParams;
import com.pos.net.netparam.RequestUrls;
import com.pos.net.request.interfa.BaseRequestListener;
import com.pos.net.request.interfa.JsonRequestListener;
import com.pos.widgets.ScanGunKeyEventHelper;

import org.json.JSONObject;

/**
 * @description:库存盘点
 * @author cai
 * @time:2018年1月30日下午10:08:29
 */
public class StorageActivity extends BaseActivity
		implements OnClickListener, ScanGunKeyEventHelper.OnScanSuccessListener {
	private EditText edit_code, edit_num;
	private TextView text_code, text_name;
	private Button button_inquery, button_upload;
	private LinearLayout linear_title_back, linear_result;
	private ImageView image_delete, image_common_title_function;
	private String goodsCode, goodsStock;
	private ScanGunKeyEventHelper mScanGunKeyEventHelper;

	@Override
	public void initView() {
		setContentView(R.layout.storage_layout);
		edit_code = bindId(R.id.edit_code);
		edit_num = bindId(R.id.edit_num);
		text_code = bindId(R.id.text_code);
		text_name = bindId(R.id.text_name);
		button_inquery = bindId(R.id.button_inquery);
		button_upload = bindId(R.id.button_upload);
		linear_title_back = bindId(R.id.linear_title_back);
		linear_result = bindId(R.id.linear_result);
		image_delete = bindId(R.id.image_delete);
		image_common_title_function = bindId(R.id.image_common_title_function);
	}

	@Override
	public void initData() {
		mScanGunKeyEventHelper = new ScanGunKeyEventHelper(this);
		registerBoradcastReceiver();
		linear_title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		image_common_title_function.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivityForResult(new Intent(mContext, ScannerActivity.class), 0);

			}
		});

	}

	@Override
	public void initListener() {
		image_delete.setOnClickListener(this);
		button_inquery.setOnClickListener(this);
		button_upload.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.image_delete:
			edit_code.setText("");
			break;
		case R.id.button_inquery:
			inqueryGoods();
			break;
		case R.id.button_upload:
			uploadGoods();
			break;

		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				goodsCode = data.getStringExtra("goodsCode");
				edit_code.setText(goodsCode);
				Log.e("goodsCode", "goodsCode=" + goodsCode);
				inqueryGoods();
			}

		}
	}

	/**
	 * 截获按键事件.发给ScanGunKeyEventHelper
	 *
	 * @param event
	 * @return
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (mScanGunKeyEventHelper.isScanGunEvent(event)) {
			mScanGunKeyEventHelper.analysisKeyEvent(event);
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onResume() {
		super.onResume();

		Log.e(Tag, "CashierActivity    onResume********");
		if (!mScanGunKeyEventHelper.hasScanGun()) {
			// Toast.makeText(mContext, "未检测到扫码枪设备", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(stateChangeReceiver);
		mScanGunKeyEventHelper.onDestroy();
	}

	@Override
	public void onScanSuccess(String barcode) {
		Log.e(Tag, "onScanSuccess barcode=" + barcode);
		System.out.println("************barcode=" + barcode);
		goodsCode = barcode;
		edit_code.setText(goodsCode);
		inqueryGoods();
	}

	private void registerBoradcastReceiver() {
		IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
		IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
		registerReceiver(stateChangeReceiver, filter1);
		registerReceiver(stateChangeReceiver, filter2);
	}

	private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
				// Toast.makeText(mContext, "蓝牙设备连接状态已变更",
				// Toast.LENGTH_SHORT).show();
			} else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
				// Toast.makeText(mContext, "蓝牙设备连接状态已变更",
				// Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	/**
	 * 查询商品
	 */
	private void inqueryGoods() {
		goodsCode = edit_code.getText().toString().trim();
		if (TextUtils.isEmpty(goodsCode)) {
			showShortToast("请输入商品码");
			return;
		}
		edit_num.setText("");
		text_code.setText("");
		text_name.setText("");
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edit_code.getWindowToken(), 0);
		netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posGetGoodsStock, Method.POST,
				NetParams.posGetGoodsStock(mContext, goodsCode), 0, listener);
	}

	/**
	 * 上传商品库存
	 */
	private void uploadGoods() {
		goodsStock = edit_num.getText().toString();
		if (TextUtils.isEmpty(goodsStock)) {
			showShortToast("请输入商品库存数量");
			return;
		}
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edit_num.getWindowToken(), 0);
		netRequest.startRequest(RequestUrls.hostUrl + RequestUrls.posSetGoodsStock, Method.POST,
				NetParams.posSetGoodsStock(mContext, goodsCode, goodsStock), 1, listener);
	}

	private BaseRequestListener listener = new JsonRequestListener() {

		@Override
		public void onStart(int requestId) {
			showDialg();
		}

		@Override
		public void onError(int requestId, int errorCode, String errorMsg) {
			disMissDialog();
			dealError(errorCode, errorMsg);

		}

		@Override
		public void onSuccess(int requestId, String url, JSONObject jsonResult) {
			disMissDialog();
			if (requestId == 0) {

				int retCode = jsonResult.optInt("retCode", 0);
				if (retCode == 1) {
					showShortToast("当前门店无该商品库存");
					linear_result.setVisibility(View.GONE);
					text_code.setText("");
					text_name.setText("");
					edit_num.setText("");
					return;
				}
				linear_result.setVisibility(View.VISIBLE);
				text_code.setText(goodsCode);
				text_name.setText(jsonResult.optString("goodsName"));
				edit_num.setText(jsonResult.optString("goodsStock"));

			} else if (requestId == 1) {
				int retCode = jsonResult.optInt("retCode", 0);
				if (retCode == 1) {
					showShortToast("上传商品库存失败");
					return;
				}

				showShortToast("上传商品库存成功");
				linear_result.setVisibility(View.GONE);
				text_code.setText("");
				text_name.setText("");
				edit_num.setText("");
				edit_code.setText("");
			}

		}
	};

}
